package com.itheima.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.*;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.ExprMapper;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private ExprMapper exprMapper;

    @Override
    public PageBean page(EmpQueryParam empQueryParam) {
        PageHelper.startPage(empQueryParam.getPage(),empQueryParam.getPageSize());
        List<Emp> empList = empMapper.list(empQueryParam);
        Page page = (Page) empList;
        PageBean pageBean = new PageBean(page.getTotal(), page.getResult());
        return pageBean;
    }

    @Override
    @Transactional
    public void save(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        empMapper.insert(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            exprList.forEach(empExpr -> {
                empExpr.setEmpId(emp.getId());
            });
            exprMapper.insertBatch(exprList);
        }
    }

    @Override
    public void delete(List<Integer> ids) {
        empMapper.deleteBatch(ids);
        exprMapper.deleteBatch(ids);
    }

    @Override
    public Emp getById(Integer id) {
        Emp emp=empMapper.getById(id);
        return emp;
    }

    @Override
    @Transactional
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);

        exprMapper.deleteByEmpId(emp.getId());

        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && exprList.size() > 0) {
            exprList.forEach(empExpr -> {
                empExpr.setEmpId(emp.getId());
            });
            exprMapper.insertBatch(exprList);
        }
    }

    @Override
    public EmpLoginInfo login(Emp emp) {
        Emp empDB=empMapper.selectUsernameAndPassword(emp);
        if(empDB!=null){
            Map<String,Object>cliams=new HashMap<>();
            cliams.put("id",empDB.getId());
            cliams.put("username",empDB.getUsername());
            String jwt = JwtUtils.generateJwt(cliams);

            return new EmpLoginInfo(empDB.getId(),empDB.getUsername(),empDB.getName(),jwt);
        }
        return null;
    }
}
